<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 * @property int $id 
 * @property string $title 标题
 * @property string $introduce 简介
 * @property array $score_option 分数设置
 * @property string $thumb 封面
 * @property string $is_publish 是否发布
 * @property int $creator_id 创建者
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 * @property-read null|\Hyperf\Database\Model\Collection|CourseTag[] $tags 
 * @property-read null|\Hyperf\Database\Model\Collection|CourseCategory[] $categorys 
 * @property-read null|\Hyperf\Database\Model\Collection|CourseSection[] $sections 
 * @property-read mixed $score_total 
 * @property-read mixed $live_rate 
 * @property-read mixed $micro_rate 
 * @property-read mixed $test_rate 
 */
class Course extends Model
{
    use Traits\HasCreator;
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'course';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'title', 'introduce', 'score_option', 'thumb', 'is_publish', 'creator_id', 'created_at', 'updated_at'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = [
        'id' => 'integer',
        'score_option' => 'json',
        'creator_id' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];


    protected array $appends = [
        'score_total',
        'live_rate',
        'test_rate',
        'micro_rate'
    ];

    public function tags()
    {
        return $this->belongsToMany(CourseTag::class, 'course_tag_pivot');
    }
    public function categorys()
    {
        return $this->belongsToMany(CourseCategory::class, 'course_category_pivot');
    }


    public function sections()
    {
        return $this->hasMany(CourseSection::class);
    }
    public function teacher(){
        return $this->creator();
    }
    public function getScoreTotalAttribute()
    {
        return array_sum(
            array_values(
                $this->score_option
            )
        );
    }
    public function getLiveRateAttribute()
    {
        return sprintf('%.2f%%', $this->score_option['live'] / $this->score_total * 100);
    }
    public function getMicroRateAttribute()
    {
        return sprintf('%.2f%%', $this->score_option['micro'] / $this->score_total * 100);
    }
    public function getTestRateAttribute()
    {
        return sprintf('%.2f%%', $this->score_option['test'] / $this->score_total * 100);
    }

    public function tasks(){
        return $this->hasMany(CourseTask::class);
    }
}
